package com.zxy.express.cos;

import com.autopai.base.common.web.exception.BusinessException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;
import com.zxy.express.exception.ModuleErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.TreeMap;

/**
 * 腾讯云存储
 *
 */

@Component
@Slf4j
public class CosService extends AbstractCosService implements InitializingBean {

    @Autowired
    CosProperties cosProperties;
    private COSCredentials credentials;
    private ClientConfig clientConfig;
    // private COSClient cosClient;
    @Autowired
    private COSClient cosClient;

    @Override
    public void afterPropertiesSet() throws Exception {
        //init();
    }

   /* private void init() {
        //1、初始化用户身份信息(secretId, secretKey)
        credentials = new BasicCOSCredentials(cosProperties.getSecretId(), cosProperties.getSecretKey());

        //2、设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        clientConfig = new ClientConfig(new Region(cosProperties.getRegion()));

        cosClient = new COSClient(credentials, clientConfig);
    }*/

    @Override
    public String upload(File file, String path) {
        String bucketName = cosProperties.getBucketName() + "-" + cosProperties.getAppId();
        PutObjectResult result = cosClient.putObject(bucketName, path, file);
        //cosClient.shutdown();
        if (result.getETag() == null) {
            throw new BusinessException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, "");
        }
        //deleteFile(file);
        return cosProperties.getDomain() + "/" + path;
    }

    public static void main(String[] args) {
       COSCredentials credentials;
       ClientConfig clientConfig;
       COSClient cosClient;
        //1、初始化用户身份信息(secretId, secretKey)
        credentials = new BasicCOSCredentials("AKIDnRs56tTr2zibHSZVEqFPL4ZqtjLjvufD", "dBYhcO0ObigUAf1CC6zugUDmKk4C9wXv");

        //2、设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        clientConfig = new ClientConfig(new Region("ap-beijing"));

        cosClient = new COSClient(credentials, clientConfig);
        String bucketName = "justmi" + "-" + "1304882443";
        long time=System.currentTimeMillis();
        String path="express/audio/张居正001.m4a";
        Path folderPath = Paths.get("D:\\BaiduNetdiskDownload\\有声读物\\存储\\张居正-熊召政\\张居正001.m4a");
        File file=new File("D:\\BaiduNetdiskDownload\\有声读物\\存储\\张居正-熊召政\\张居正001.m4a");
        PutObjectResult result = cosClient.putObject(bucketName, path, folderPath.toFile());
        //cosClient.shutdown();
        if (result.getETag() == null) {
            throw new BusinessException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, "");
        }
        System.out.println("https://justmi-1304882443.cos.ap-beijing.myqcloud.com/"+path);
        //return cosProperties.getDomain() + "/" + path;
    }



    @Override
    public String uploadSuffix(MultipartFile file, String suffix) throws IOException {
        File tempFile = File.createTempFile(file.getOriginalFilename(), suffix);
        file.transferTo(tempFile);
        return upload(tempFile, getPath(cosProperties.getPrefix(), suffix));
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            String bucketName = cosProperties.getBucketName() + "-" + cosProperties.getAppId();
            PutObjectRequest request = new PutObjectRequest(bucketName, path, inputStream, metadata);
            PutObjectResult result = cosClient.putObject(request);

            //cosClient.shutdown();
            if (result.getETag() == null) {
                throw new BusinessException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, "");
            }
        } catch (IOException e) {
            log.error("oss上传失败", e);
            throw new BusinessException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, "oss上传失败");
        }

        return cosProperties.getDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(cosProperties.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(cosProperties.getPrefix(), suffix));
    }


    public boolean isExist(String cosPath) {
        if (StringUtils.isEmpty(cosPath)) {
            return false;
        }
        try {
            if (cosPath.startsWith("http")) {
                cosPath = cosPath.substring(cosPath.indexOf("/", 10));
            }
            return cosClient.doesObjectExist(cosProperties.getBucketName()+"-"+cosProperties.getAppId(), cosPath);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

        /**
         * 获取JS-web端上传腾讯云cos临时秘钥
         * 一次有效 2小时有效期
         * @param
         * @return
         */
//    public Response getJsUploadCredential(){
//        TreeMap<String, Object> config = new TreeMap<String, Object>();
//
//        try {
//
//            // 云 api 密钥 SecretId
//            config.put("secretId", cosProperties.getSecretId());
//            // 云 api 密钥 SecretKey
//            config.put("secretKey", cosProperties.getSecretKey());
//
//
//            // 设置域名,可通过此方式设置内网域名
//            //config.put("host", "sts.internal.tencentcloudapi.com");
//
//            // 临时密钥有效时长，单位是秒
//            config.put("durationSeconds", 2 * 60 * 60);
//
//            // 换成你的 bucket
//            config.put("bucket", cosProperties.getBucketName() +"-"+cosProperties.getAppId());
//            // 换成 bucket 所在地区
//            config.put("region", cosProperties.getRegion());
//
//            // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
//            config.put("allowPrefixes", new String[] {
//                    "*"
//            });
//
//            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
//            String[] allowActions = new String[] {
//                    // 简单上传
//                    "name/cos:PutObject",
//                    "name/cos:PostObject",
//                    // 分片上传
////                    "name/cos:InitiateMultipartUpload",
////                    "name/cos:ListMultipartUploads",
////                    "name/cos:ListParts",
////                    "name/cos:UploadPart",
////                    "name/cos:CompleteMultipartUpload"
//            };
//            config.put("allowActions", allowActions);
//
//            response = CosStsClient.getCredential(config);
//            System.out.println(response.credentials.tmpSecretId);
//            System.out.println(response.credentials.tmpSecretKey);
//            System.out.println(response.credentials.sessionToken);
//            return response;
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new IllegalArgumentException("no valid secret !");
//        }
//    }


    public void copyObject(String srcKey, String destKey) {
        String bucketName = cosProperties.getBucketName() + "-" + cosProperties.getAppId();
        CopyObjectRequest request = new CopyObjectRequest(bucketName, srcKey, bucketName, destKey);
        cosClient.copyObject(request);
        //cosClient.shutdown();
    }

    public byte[] download(String key) {
        String bucketName = cosProperties.getBucketName() + "-" + cosProperties.getAppId();
        try {
            COSObject clientObject = cosClient.getObject(bucketName, key);
            COSObjectInputStream inputStream = clientObject.getObjectContent();
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            log.error("oss下载失败", e);
        }
        return null;
    }
}